package com.xcity.game.skill.v2;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.xcity.db.entity.Employee;
import com.xcity.db.entity.Player;
import com.xcity.game.combat.unit.Combatable;
import com.xcity.game.employee.EmployeeUtils;
import com.xcity.game.employee.template.EmployeeTemplate;
import com.xcity.game.skill.template.SkillTemplate;

public class SkillManagerV2 {

	private Combatable owner;
	private DefaultSkillV2 active; // 主动技能
	private List<DefaultSkillV2> passives; // 被动技能
	
	public SkillManagerV2(Combatable owner, List<DefaultSkillV2> skills) {
		this.owner = owner;
		this.passives = new ArrayList<>(skills.size() - 1);
		for (int i = 0, size = skills.size(); i < size; i++) {
			DefaultSkillV2 skill = skills.get(i);
//			skill.setVm(this);
			if (skill.getTemplate().getType() == SkillTemplate.TYPE_ACTIVE) {
				this.active = skill;
			} else {
				this.passives.add(skill);
			}
		}
	}
	
	public SkillManagerV2(Combatable owner, DefaultSkillV2 active, List<DefaultSkillV2> passives) {
		this.active = active;
		this.passives = passives;
		this.setOwner(owner);
	}
	
	private void init() {
		Combatable owner = this.owner;
		EmployeeTemplate et;
		if (owner instanceof Player) {
			et = EmployeeUtils.getPlayerTemplate();
		} else if (owner instanceof Employee) {
			et = ((Employee) owner).getTemplate();
		} else { // !!impossible
			return;
		}
		this.active.setVm(this);
		// 初始化被动技能解锁等级
		List<DefaultSkillV2> passives = this.passives;
		int[] unlockStarLvls = et.getPassiveSkillUnlockStarLvls();
		for (int i = 0, size = passives.size(); i < size; i++) {
			DefaultSkillV2 passive = passives.get(i);
			passive.setVm(this);
			passive.setUnlockStarLvl(unlockStarLvls[i]);
		}
	}
	
	public Combatable getOwner() {
		return owner;
	}
	
	public void setOwner(Combatable owner) {
		if (this.owner != owner) {
			this.owner = owner;
			init();
		}
	}
	
	public DefaultSkillV2 getActive() {
		return active;
	}
	
	public List<DefaultSkillV2> getPassives() {
		return passives;
	}
	
	public int size() {
		return passives.size() + 1;
	}
	
	public DefaultSkillV2 get(int id) {
		if (id == active.getId()) {
			return active;
		}
		for (int i = passives.size() - 1; i >= 0; i--) {
			DefaultSkillV2 skill = passives.get(i);
			if (skill.getId() == id) {
				return skill;
			}
		}
		return null;
	}
	
	@Override
	public String toString() {
		List<DefaultSkillV2> list = new ArrayList<>(passives.size() + 1);
		list.add(active);
		list.addAll(passives);
		return JSON.toJSONString(list);
	}
	
	
}
